/******************************************************************
 * Created by: GOh Chee Hong                                      
 * Date of Creation: 1/Jan/2009

 * 
 *                                                                
 * Description: This class is in sending an instant message
 ******************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using Pbdms.BusinessLogic;
using Pbdms.NetworkDealer;
using Pbdms.Common.DataObject;
namespace Pbdms.BusinessLogic.InstantMessaging
{
    public class InstantMessager
    {
     ///................
        public delegate void FailedToSendHandler(object sender, string message);
        public event FailedToSendHandler FailedToSend;
        private string message;
        private string keyID;
        private BusinessLogic.Network.NetworkController networkController;
        public InstantMessager(string message, string keyID, BusinessLogic.Network.NetworkController networkController)
        {
            this.message = message;
            this.keyID = keyID;
            this.networkController = networkController;
        }
        public void sendMessage()
        {
            Buddy buddy = networkController.friendsControl.getAFriendByKeyID(keyID);
            try
            {
                //...................
                AuthTcpClient authClient = new AuthTcpClient(buddy.IpAdd, NetworkDealer.NetworkDealer.LISTEN_PORT, buddy.KeyID, networkController.keyControl, networkController.publicKeyControl, networkController.friendsControl);
                authClient.Connect();
                if (!authClient.IsAuthenticated())
                {
                    throw new Exception("Not Trusted friend");
                }          
                //send a message
                NetworkMessage Networkmessage = new NetworkMessage();
                Networkmessage.TypeOfMessage = NetworkDealer.NetworkDealer.SEND_A_MESSAGE;
                Networkmessage.MessageContent = message;
                authClient.sendMessage(Networkmessage);
                NetworkMessage reply = authClient.receiveMessage();
                if (NetworkDealer.NetworkDealer.SEND_A_MESSAGE_REPLY != reply.TypeOfMessage)
                {
                    throw new Exception();
                }
            }
            catch
            {
                if (FailedToSend != null)
                {
                    FailedToSend(this, message);
                }
            }
        }
        public string Message
        {
            get { return message; }
        }
    }
}
